package com.example.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.common.ResponseData;
import com.example.controller.base.BaseController;
import com.example.service.ToolService;

import net.sf.image4j.codec.ico.ICOEncoder;

@CrossOrigin
@RestController
@RequestMapping("/tool")
public class ToolController extends BaseController {

	@Autowired
	private ToolService toolService;

	@Value("${upload.cachedir}")
	private String cachedir;

	@RequestMapping(value = "icoupload", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData icoupload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("file") MultipartFile file, @RequestParam("size") Integer size) {
		ResponseData responseData = new ResponseData();
		try {
			BufferedImage resizedImage = toolService.resizeImage(ImageIO.read(file.getInputStream()), size, size);
			File icoPath = new File(cachedir + "/ico");
			if (!icoPath.exists() && !icoPath.isDirectory()) {
				icoPath.mkdirs();
			}
			File icoFile = new File(icoPath.getAbsolutePath() + "/favicon-" + System.currentTimeMillis() + "-" + size
					+ "x" + size + ".ico");
			ICOEncoder.write(resizedImage, icoFile);
			responseData.setData(icoFile.getName());
			responseData.setRetcode(SUCCESS);
			responseData.setMsg("上传成功");
		} catch (IOException e) {
			e.printStackTrace();
			responseData.setRetcode(FAIL);
			responseData.setMsg("上传失败");
		}
		return responseData;
	}

}
